package com.yima.baseproj.module.sys.user;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yima.baseproj.module.sys.user.model.*;
import com.yima.baseproj.module.sys.user.model.SysUserAddParamModel;
import com.yima.baseproj.module.sys.user.model.SysUserEditParamModel;
import com.yima.baseproj.module.sys.user.model.UserProfile;
import com.yima.baseproj.module.sys.user.model.UserSearchAddOrEditModel;
import com.yima.baseproj.module.sys.user.role.SysUserRoleEntity;
import com.yima.baseproj.module.sys.user.role.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class SysUserService extends ServiceImpl<SysUserMapper, SysUserEntity> {

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Value("${upload.webBasePath}")
    private String webbasepath;

    public Page<Map> findAllByPage(Page page, UserSearchAddOrEditModel searchModel) {
        return baseMapper.findBySearchVo(page,searchModel);
    }

    public SysUserEntity checkSysUserUnique(String loginName) {
        return getOne(Wrappers.<SysUserEntity>query().eq("login_name",loginName));
    }

    public SysUserEntity findByLoginName(String loginName) {
        return getOne(Wrappers.<SysUserEntity>query().eq("login_name",loginName));
    }

    @Transactional(rollbackFor = Exception.class)
    public void add(SysUserAddParamModel paramModel) {
        SysUserEntity userEntity = new SysUserEntity();
        userEntity.setSysUserEntity(paramModel);
        if(StrUtil.isBlank(userEntity.getHeadUrl())){
            userEntity.setHeadUrl(String.format("%s/app/headimg/headimg.png",webbasepath));
        }
        String salt = BCrypt.gensalt();
        userEntity.setSalt(salt);
        userEntity.setPassword(BCrypt.hashpw(paramModel.getPassword(),salt));
        baseMapper.insert(userEntity);
        saveUserRole(userEntity.getId(), paramModel.getRoleIdList());
    }

    @Transactional(rollbackFor = Exception.class)
    public void edit(SysUserEditParamModel paramModel) {
        SysUserEntity userEntity = baseMapper.selectById(paramModel.getId());
        userEntity.setSysUserEntity(paramModel);
        if(StrUtil.isBlank(userEntity.getHeadUrl())){
            userEntity.setHeadUrl(String.format("%s/sys/headimg/headimg.png",webbasepath));
        }
        baseMapper.updateById(userEntity);
        saveUserRole(userEntity.getId(), paramModel.getRoleIdList());
    }

    private void saveUserRole(String userid, List<String> roleIdList) {
        sysUserRoleService.delByUserId(userid);
        if (!Objects.isNull(roleIdList) && !roleIdList.isEmpty()) {
            List<SysUserRoleEntity> roleList = CollectionUtil.newArrayList();
            for (String roleId : roleIdList) {
                SysUserRoleEntity sysUserRole = new SysUserRoleEntity();
                sysUserRole.setRoleId(roleId);
                sysUserRole.setUserId(userid);
                roleList.add(sysUserRole);
            }
            sysUserRoleService.saveBatch(roleList);
        }

    }

    public boolean hasDeptUser(String deptId) {
        return count(Wrappers.<SysUserEntity>query().eq("dept_id",deptId)) > 0;
    }

    public UserProfile getUserProfile(String userId) {
        return baseMapper.selectProfileById(userId);
    }

    @Transactional(rollbackFor = Exception.class)
    public void delByIds(String[] ids) {
        for (String id : ids) {
            //彻底删除
            sysUserRoleService.delByUserId(id);
            //彻底删除
            baseMapper.deleteById(id);
        }
    }
}